package com.example.cglib;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class ProxyFactory implements MethodInterceptor {
    
    private Object target;

    /**
     * 被代理的对象
     */
    public ProxyFactory(Object obj) {
        this.target = obj;
    }
    
    public Object getProxyInstance() {
        // 创建工具类
        Enhancer enhancer = new Enhancer();
        // 设置父类
        enhancer.setSuperclass(target.getClass());
        // 回调函数
        enhancer.setCallback(this);
        // 返回子类对象
        return enhancer.create();
    }

    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        System.out.println("cglib proxy start");
        Object result = method.invoke(target, args);
        System.out.println("cglib proxy end");
        return result;
    }
}
